# -*- coding: utf-8 -*-
import os
import sys
import threading
from multiprocessing.pool import ThreadPool
from shutil import copyfile

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtWidgets import QFileDialog, QTableWidgetItem
from openpyxl import load_workbook

import commonFunc
from MainForm import Ui_MainWindow

global_num = 0
tot_deal_num = 0
sucNum = 0


class Position:
    def __init__(self, name, sheet_index, row, column):
        self.name = name
        self.sheetIndex = sheet_index
        self.row = row
        self.column = column


class CopyFileInfo:
    def __init__(self, copy_source_path, copy_target_path, copy_import_values, copy_position_list, is_copy_flag, row_index):
        self.copySourcePath = copy_source_path
        self.copyTargetPath = copy_target_path
        self.copyImportValues = copy_import_values
        self.copyPositionList = copy_position_list
        self.isCopyFlag = is_copy_flag
        self.rowIndex = row_index


class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    printProgressBarSendMsg = pyqtSignal(object, object)
    list = []
    importFileName = ""
    copyFileInfoList = []

    def __init__(self):
        super(MyWindow, self).__init__()
        self.setupUi(self)
        self.setFixedSize(self.width(), self.height())

    def select_file(self):
        self.set_btn_visible(False, False, False)
        file_name = self.open_file_name("E:/", "*.xls;*.xlsx")
        if self.is_empty(file_name):
            self.set_btn_visible(True, True, True)
            return

        self.clear_all()
        self.tableWidget.clear()
        self.add_position(file_name)
        self.importFileName = file_name
        self.set_btn_visible(True, True, True)

    def open_file_name(self, path, file_list):
        file_name = QFileDialog.getOpenFileName(self, u"选取文件", path, "Text Files (" + file_list + ")")  # 设置文件扩展名过滤,注意用双分号间隔
        return file_name[0]

    def add_position(self, path):
        self.list.clear()
        self.find_comment_in_excel(path)
        self.tableWidget.setColumnCount(len(self.list) + 2)

        header_list = []
        if self.radioButtonWriteFile.isChecked():
            header_list.append("文件名(包含)")
        if self.radioButtonCopyFile.isChecked():
            header_list.append("文件名(生成)")

        for pos in self.list:
            header_list.append(pos.name)
        header_list.append("处理结果")
        self.tableWidget.setHorizontalHeaderLabels(header_list)

    def generate(self):
        self.set_btn_visible(False, False, False)
        file_name = QFileDialog.getExistingDirectory(self, "请选择模板保存路径...", "E:/")
        if self.is_empty(file_name):
            self.set_btn_visible(True, True, True)
            return
        file_names = self.importFileName.split(".")

        is_copy_flag = True

        dir_file_names = []
        if self.radioButtonWriteFile.isChecked():
            is_copy_flag = False
            dir_file_names = os.listdir(file_name)

        global tot_deal_num
        tot_deal_num = self.tableWidget.rowCount()

        self.copyFileInfoList.clear()
        for i in range(self.tableWidget.rowCount()):
            import_values = []
            target_path = ""
            for j in range(self.tableWidget.columnCount() - 1):
                item_value = self.tableWidget.item(i, j).text()
                if j == 0:

                    if is_copy_flag:
                        target_path = file_name + "/" + item_value + "." + file_names[len(file_names) - 1]
                    else:
                        target_path = file_name + "/" + commonFunc.find_str_in_list(item_value, dir_file_names)
                else:
                    import_values.append(item_value)

            cp = CopyFileInfo(self.importFileName if is_copy_flag else target_path, target_path, import_values, self.list, is_copy_flag, i)
            self.copyFileInfoList.append(cp)

        thread_bar = threading.Thread(target = self.do_thread)
        thread_bar.start()

    def do_thread(self):
        pool = ThreadPool(processes=3)
        for copyFileInfo in self.copyFileInfoList:
            pool.map(self.do_copy_file(copyFileInfo.copySourcePath, copyFileInfo.copyTargetPath, copyFileInfo.copyImportValues, copyFileInfo.copyPositionList, copyFileInfo.isCopyFlag, copyFileInfo.rowIndex), range(0))
        pool.close()
        pool.join()
        print("finish")

    def import_argument(self):
        self.set_btn_visible(False, False, False)
        file_name = self.open_file_name("E:/", "*.xls;*.xlsx")
        if self.is_empty(file_name):
            self.set_btn_visible(True, True, True)
            return

        self.clear_all()
        self.read_excel(file_name)
        self.set_btn_visible(True, True, True)

    def remove_all_table_rows(self):
        row_count = self.tableWidget.rowCount()
        for i in range(row_count):
            self.tableWidget.removeRow(0)

    def clear_all(self):
        global global_num
        global tot_deal_num
        global sucNum
        global_num = 0
        tot_deal_num = 0
        sucNum = 0
        self.remove_all_table_rows()

    def read_excel(self, path):
        read_workbook = load_workbook(path)
        read_worksheets = read_workbook.sheetnames
        read_worksheet = read_workbook[read_worksheets[0]]
        num_rows = read_worksheet.max_row
        num_cols = read_worksheet.max_column
        for row in range(num_rows):
            self.tableWidget.insertRow(row)
            for col in range(num_cols):
                cell = read_worksheet.cell(row + 1, col + 1)
                if cell is not None:
                    self.tableWidget.setItem(row, col, QTableWidgetItem(str(cell.value).strip()))
            self.tableWidget.setItem(row, num_cols, QTableWidgetItem("待处理.."))
        read_workbook.close()

    def find_comment_in_excel(self, path):
        workbook = load_workbook(path)
        worksheets = workbook.sheetnames
        sheet_index = 1
        for sheet in worksheets:
            worksheet1 = workbook[u'' + sheet]
            num_rows = worksheet1.max_row
            num_cols = worksheet1.max_column
            for row in range(num_rows):
                for col in range(num_cols):
                    cell = worksheet1.cell(row + 1, col + 1).value
                    if cell is not None:
                        if str(cell).count("$") == 2:
                            pos = Position(str(cell).strip(), sheet_index, row + 1, col + 1)
                            self.list.append(pos)
            sheet_index = sheet_index + 1
        workbook.close()

    def set_progress_bar_value(self, cur_value, tot_value):
        if cur_value >= tot_value:
            self.progressBar.setValue(100)
        else:
            self.progressBar.setValue(round((cur_value + 1) * 100 / tot_value))

    def print_progress_bar_value(self, print_row_index, print_result):
        self.set_deal_result(print_row_index, print_result)
        global global_num
        global tot_deal_num
        global sucNum
        global_num += 1
        if print_result == "完成...":
            sucNum += 1
        self.set_progress_bar_value(global_num, tot_deal_num)
        if global_num >= tot_deal_num:
            self.set_btn_visible(True, True, True)
            show_message = "执行完成，成功" + str(sucNum) + "笔"
            commonFunc.message_showinfo("提示", show_message)

    def set_btn_visible(self, select_btn_bool, import_btn_bool, generate_btn_bool):
        self.pushButtonSelectFile.setEnabled(select_btn_bool)
        self.pushButtonImportArgument.setEnabled(import_btn_bool)
        self.pushButtonGenerate.setEnabled(generate_btn_bool)

    @staticmethod
    def is_empty(string):
        if string is None:
            return True

        if string == "":
            return True

        return False

    def set_deal_result(self, row_index, result):
        self.tableWidget.setItem(row_index, self.tableWidget.columnCount() - 1, QTableWidgetItem(result))
        self.tableWidget.item(row_index, self.tableWidget.columnCount() - 1).setForeground(QBrush(QColor(255, 0, 0)))

    def do_copy_file(self, source_file_path, target_file_path, item_value, position_list, is_copy_flag, table_row_index):
        return_result = "完成..."
        try:
            if is_copy_flag:
                copyfile(source_file_path, target_file_path)

            write_workbook = load_workbook(target_file_path)
            write_worksheets = write_workbook.sheetnames
            index = 0
            for pos in position_list:
                write_worksheet = write_workbook[write_worksheets[pos.sheetIndex - 1]]
                if len(item_value) <= index:
                    break
                item_value_name = str(pos.name).strip()
                find_index = item_value_name.find("$")
                rfind_index = item_value_name.rfind("$") + 1
                replace_item_value = item_value_name[find_index:rfind_index]
                write_worksheet.cell(pos.row, pos.column, item_value_name.replace(replace_item_value, item_value[index]))
                index = index + 1
            write_workbook.save(target_file_path)
            write_workbook.close()
        except Exception as e:
            print(e)
            return_result = str(e)
        finally:
            self.printProgressBarSendMsg.emit(table_row_index, return_result)

if __name__ == "__main__":
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.printProgressBarSendMsg.connect(window.print_progress_bar_value)
    window.show()
    sys.exit(app.exec_())